package cac.fenjian.resource.PointPackageSort.service;

import cac.fenjian.resource.PointPackageSort.dao.PackageAoQueryDao;
import cac.fenjian.resource.PointPackageSort.dao.PointPackageDao;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.cac.dme.adapter.utils.ComUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.Objects;

@Slf4j
@Service
public class PackageAoQueryService {
    @Autowired
    private PackageAoQueryDao packageAoQueryDao;
    @Autowired
    private PointPackageDao pointPackageDao;
    @Transactional
    public ResponseMsg handleMatch(HashMap map){
        String msAoMatchInfoId = ComUtil.getId();
        map.put("msAoMatchInfoId",msAoMatchInfoId);
        //查询此本AO对应的托盘是否被相同架次的工作包使用过
        String toolCode = pointPackageDao.queryToolCodeByPackage(map);
        if(!Objects.isNull(toolCode)){
            map.put("toolCode",toolCode);
        }else{
            toolCode = pointPackageDao.queryToolCodeByRule(map);
            if(!Objects.isNull(toolCode)){
                map.put("toolCode",toolCode);
            }else{
                map.put("toolCode","无");
            }

        }
        //往 ms_ao_match_info表插入一条记录
        packageAoQueryDao.addMatchInfo(map);
        //往ms_assgin_workbintool_rel插入一条记录
        packageAoQueryDao.insertAssignWorkbinToolRelByMatchInfoId(map);
        //更新ms_task_ao表状态
        packageAoQueryDao.updateMsTaskAoState(map);
        //更新ms_task_package表状态
        packageAoQueryDao.updateTaskPackageState(map);
        return new ResponseMsg().setRetCode("200").setMessage("配套成功");
    }

    @Transactional
    public ResponseMsg remmoveMatchInfo(HashMap map){
        try{
            packageAoQueryDao.remmoveMatchInfo(map);
            packageAoQueryDao.removeAssginInfo(map);
            return new ResponseMsg().setRetCode("200").setMessage("移除配套信息成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseMsg().setRetCode("201").setMessage("移除配套信息失败");
        }
    }

}
